package com.zjj.disk.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjj.disk.controller.result.Result;
import com.zjj.disk.mapper.UserInfoMapper;
import com.zjj.disk.mapper.UserMapper;
import com.zjj.disk.pojo.UserInfo;
import com.zjj.disk.service.IUserInfoService;
import com.zjj.disk.utils.WebUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author zjj
 * @create 2023-04-11 19:51
 */
@Service
@Transactional
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Autowired
    private UserInfoMapper mapper;
    @Autowired
    private UserMapper userMapper;
    @Value("${application.avatarfile}")
    private String avatarRootPath;

    @Override
    public Result getUserInfo() {
        Integer loginId = WebUtil.getLoginId();
        UserInfo userInfo = mapper.getUserInfo(loginId);
        if (userInfo == null) {
            return new Result().fail().addMsg("用户不存在！");
        } else {
            StringBuffer doEmail = new StringBuffer(userInfo.getEmail());
            int i = doEmail.indexOf("@");
            doEmail.replace(1, i - 1, "***");
            userInfo.setEmail(doEmail.toString());
        }
        return new Result().success().addMsg("查询成功！").addData("userInfo", userInfo);
    }

    @Override
    public Result uploadAvatar(MultipartFile avatarFile) {
        // 验证文件扩展名
        String ext = FilenameUtils.getExtension(avatarFile.getOriginalFilename());
        if (!"jpg".equalsIgnoreCase(ext)) {
            return new Result().fail().addMsg("文件类型有误，只能是JPG格式");
        }

        // 验证文件内容是否为图片
        if (!isImage(avatarFile)) {
            return new Result().fail().addMsg("文件内容不是有效的图片");
        }
        String avatarUrl = "";
        try {
            Integer loginId = WebUtil.getLoginId();
            String location = avatarRootPath + loginId + "/";

            // 创建目录
            File dir = new File(location);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            HttpServletRequest request = WebUtil.getRequest();
            avatarUrl = request.getScheme() + "://"
                    + request.getServerName() + ":"
                    + request.getServerPort()
                    + request.getContextPath()
                    + "/static/avatar/" + loginId + "/avatar.jpg";

            UserInfo userInfo = mapper.getUserInfo(loginId);
            userInfo.setAvatarUrl(avatarUrl);
            mapper.updateById(userInfo);

            // 删除旧文件
            File oldFile = new File(location + "avatar.jpg");
            if (oldFile.exists()) {
                oldFile.delete();
            }

            // 保存新文件
            avatarFile.transferTo(new File(location + "avatar.jpg"));

        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e); // 保留原始异常信息
        }

        return new Result().success().addMsg("上传成功！").addData("avatarUrl", avatarUrl);
    }

    private static final Tika tika = new Tika();

    public static boolean isImage(MultipartFile file) {
        try {
            String mimeType = tika.detect(file.getInputStream());
            return mimeType.startsWith("image/");
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Result changeInfo(UserInfo userInfo) {
        Integer loginId = WebUtil.getLoginId();
        if (userInfo.getCreatorId() != loginId) {
            return new Result().fail().addMsg("用户无法进行此操作");
        } else {
            userInfo.setAvatarUrl(null);
            userInfo.setEmail(null);
            mapper.updateById(userInfo);
        }
        Result result = getUserInfo();
        userMapper.updateUsername(userInfo.getUsername(), loginId);
        return new Result().success().addMsg("修改成功!").addData("userInfo", result.getData().get("userInfo"));
    }
}
